package com.jinke.api.modules.ums.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.common.exception.Asserts;
import com.jinke.api.modules.app.enums.MemberType;
import com.jinke.api.modules.app.model.UmsSubscribeLog;
import com.jinke.api.modules.app.request.OrderListRequest;
import com.jinke.api.modules.app.request.TrackRequest;
import com.jinke.api.modules.app.response.MilestoneVO;
import com.jinke.api.modules.app.response.UserOrderParcelTrackVO;
import com.jinke.api.modules.app.service.UmsSubscribeLogService;
import com.jinke.api.modules.app.service.UserRechargeService;
import com.jinke.api.modules.third.trackApi.TrackApiUtils;
import com.jinke.api.modules.ums.model.UmsAdmin;
import com.jinke.api.modules.ums.request.RechargeRequest;
import com.jinke.api.security.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@Api(value = "物流管理", tags = "物流管理")
@RequestMapping("/admin/track")
@Slf4j
public class UmsTrackController {

    @Resource
    UserRechargeService userRechargeService;

    @Resource
    UmsSubscribeLogService subscribeLogService;

    @ApiOperation("订阅充值")
    @PostMapping("/recharge")
    @ResponseBody
    public CommonResult<?> recharge(@RequestBody RechargeRequest request) {
        return CommonResult.success(userRechargeService.recharge(request));
    }

    @ApiOperation("充值记录")
    @RequestMapping(value = "/getTrackInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<UserOrderParcelTrackVO>> getTrackInfo(@RequestBody TrackRequest request) {
        UmsAdmin userInfo = AdminUserUtil.getUserInfo();
        if (userInfo.getMemberType().equals(MemberType.USER)) {
            if (!isUserSub()) {
                Asserts.fail("请先订阅");
            }
        }
        Gson gson = new Gson();
        int batchSize = 40;
        List<String> numbers = Arrays.asList(request
                .getTrackingNos().replace("，", ",").split(","));
        List<UserOrderParcelTrackVO> userOrderParcelTrackVOList=new ArrayList<>();
        for (int i = 0; i < numbers.size(); i += batchSize) {

            List<String> batch = numbers.subList(i, Math.min(numbers.size(), i + batchSize));
            String trackinfo = TrackApiUtils.getTrackinfo(batch);
            if (trackinfo==null){
                continue;
            }
            JSONObject jsonBody = JSON.parseObject(trackinfo);
            Integer code = jsonBody.getInteger("code");
            if (code==0){

                JSONObject data = jsonBody.getJSONObject("data");
                JSONArray accepted = data.getJSONArray("accepted");
                JSONArray rejected = data.getJSONArray("rejected");
                for (int i1 = 0; i1 < accepted.size(); i1++) {
                    UserOrderParcelTrackVO userOrderParcelTrackVO = new UserOrderParcelTrackVO();
                    JSONObject item = accepted.getJSONObject(i1);
                    // 在这里对每个 item 进行处理
                   // System.out.println(item);
                    log.info("item:{}", item);
                    String number = item.getString("number");
                    //物流信息主结构节点。
                    JSONObject track_info = item.getJSONObject("track_info");

                    JSONArray milestone = track_info.getJSONArray("milestone");

                    List<MilestoneVO> milestoneList = gson.fromJson(milestone.toString(), new TypeToken<List<MilestoneVO>>(){}.getType());

                    userOrderParcelTrackVO.setNumber(number);
                    userOrderParcelTrackVO.setMilestone(milestoneList);
                    userOrderParcelTrackVOList.add(userOrderParcelTrackVO);
                }
                for (int j = 0; j < rejected.size(); j++) {
                    UserOrderParcelTrackVO userOrderParcelTrackVO = new UserOrderParcelTrackVO();
                    JSONObject item = rejected.getJSONObject(j);
                    // 在这里对每个 item 进行处理
                    System.out.println(item);
                    String number = item.getString("number");
                    //物流信息主结构节点。
                    JSONObject error = item.getJSONObject("error");

                     String message = error.getString("message");


                    userOrderParcelTrackVO.setNumber(number);
                    userOrderParcelTrackVO.setMessage(message);
                    userOrderParcelTrackVOList.add(userOrderParcelTrackVO);
                }
            }

        }
        //page分页<数据库类> list = 充值记录接口的list功能(返回请求)
        return CommonResult.success(userOrderParcelTrackVOList);
    }


    /**
     * @Author: hhp
     * @Description: 当前用户是否有订阅记录
     * @Data: 2024/7/26 13:41
     * @param
     * @return: boolean true:有订阅记录 false:无订阅记录
     * @throws:
     **/
    private boolean isUserSub() {
        List<UmsSubscribeLog> list = subscribeLogService.list(new LambdaQueryWrapper<UmsSubscribeLog>().eq(UmsSubscribeLog::getUserId, AdminUserUtil.getUserId()).select(UmsSubscribeLog::getId));
        return CollUtil.isNotEmpty(list);
    }
}
